// 关于购物车操作的接口
var express = require("express");
var router = express.Router();
var mongo = require("./db")
// 操作数据库id
var mongodb = require("mongodb");
var ObjectId = mongodb.ObjectId;

router.post("/addcart", function (req, res) {
  // 商品id  名称 商品id  商店名称  商品图片 价格  数量
  var cartinfo = {
    goods_id: req.body.goods_id,
    goods_name: req.body.goods_name,
    price: req.body.price,
    image: req.body.image,
    oldprice: req.body.oldprice,
    stroename: req.body.stroename,
    storeId: req.body.storeId
  }

  mongo("find", "cartlist", { goods_id: req.body.goods_id }, function (data) {
    if (data.length == 0) {  //如果商品未添加过 添加商品
      cartinfo.num = Number(req.body.num);
      mongo("insert", "cartlist", cartinfo, function () {
        res.send({ success: "添加购物车成功" })
      })
    } else {  // 如果商品有添加过 更新数量
      var num = Number(data[0].num) + Number(req.body.num);
      mongo("update", "cartlist", [{ goods_id: req.body.goods_id }, { num: num }], function () {
        res.send({ success: "更新购物车成功" })
      })
    }
  })
})
// 查询购物车的数据
router.post("/findCart", function (req, res) {
  mongo("find", "cartlist", {}, function (data) {
    res.send(data)//把查询到的购物车数据返回给前端
  })
})
// 删除购物车数据
router.post("/del", function (req, res) {
  mongo("del", "cartlist", { _id: ObjectId(req.body._id) }, function () {
    res.send({ success: "删除成功" })
  })
})
// 获取购物车数量的接口
router.post("/cartnum", function (req, res) {
  mongo("find", "cartlist", {}, function (data) {
    res.send({ cartnum: data.length })
  })
})
// 单选接口 选中1  未选中未0
router.post("/ischeck", function (req, res) {
  // 判断当前商店是否全选
  mongo("update", "cartlist", [{ _id: ObjectId(req.body._id) }, { is_check: req.body.is_check }], function () {
    mongo("find", "cartlist", { storeId: req.body.storeId }, function (data) {
      var flag = true;
      for (var i = 0; i < data.length; i++) {
        if (data[i].is_check == "0") {
          flag = false;
        }
      }
      if (flag) {
        mongo("updateMany", "cartlist", [{ storeId: req.body.storeId }, { isall: "1" }], function () { })
      } else {
        mongo("updateMany", "cartlist", [{ storeId: req.body.storeId }, { isall: "0" }], function () { })
      }
      res.send({ success: "修改成功" })
    })
  })
})
// 店铺全选接口
router.post("/storeAll", function (req, res) {
  mongo("updateMany", "cartlist", [{ storeId: req.body.storeId }, { is_check: req.body.is_check, isall: req.body.is_check }], function () {
    res.send({ success: "改变成功" })
  })
})
//购物车全选接口
router.post("/allcheck", function (req, res) {
  mongo("updateMany", "cartlist", [{}, { isall: req.body.all, is_check: req.body.all }], function () {
    res.send({ success: "改变成功" })
  })
})
// 更新购物车数量的接口
router.post("/updateNum", function (req, res) {
  mongo("update", "cartlist", [{ _id: ObjectId(req.body._id) }, { num: req.body.num }], function () {
    res.send({ success: "更新商品数量成功" })
  })
})

module.exports = router;